package com.android.webrtcsdkdev

import android.annotation.SuppressLint
import android.app.Activity
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.os.*
import android.util.Log
import android.view.View
import android.view.Window
import android.view.WindowManager.LayoutParams
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.Toast
import com.android.webrtcsdkdev.net.ApiJavaClient
import com.android.webrtcsdkdev.net.ICallback
import com.android.webrtcsdkdev.settingDialog.AppRootDialog
import com.android.webrtcsdkdev.settingDialog.ClipboardDialog
import com.android.webrtcsdkdev.settingDialog.DisplayAppDialog
import com.android.webrtcsdkdev.settingDialog.HideAppDialog
import com.android.webrtcsdkdev.settingDialog.IRequesListener1
import com.android.webrtcsdkdev.settingDialog.IRequesListener2
import com.android.webrtcsdkdev.settingDialog.IRequesListener3
import com.android.webrtcsdkdev.settingDialog.IRequesListener4
import com.android.webrtcsdkdev.settingDialog.IRequesListener5
import com.android.webrtcsdkdev.settingDialog.IRequesListener6
import com.android.webrtcsdkdev.settingDialog.IRequesListener7
import com.android.webrtcsdkdev.settingDialog.SettingDpiDialog
import com.android.webrtcsdkdev.settingDialog.SettingResolutionDialog
import com.android.webrtcsdkdev.settingDialog.StartAppDialog
import com.android.webrtcsdkdev.settingDialog.StartPreviewDialog
import com.android.webrtcsdkdev.settingDialog.StopAppDialog
import com.android.webrtcsdkdev.settingDialog.StopPreviewDialog
import com.android.webrtcsdkdev.settingDialog.SystemRootDialog
import com.android.webrtcsdkdev.settingDialog.UninstallAppDialog
import com.android.webrtcsdkdev.settingDialog.VirtualLocationDialog
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.vc.videosdk.Constant
import com.vc.videosdk.VcOperateManager
import com.vc.videosdk.VcSurfaceView
import com.vc.videosdk.custom.OperatorListener
import com.vc.videosdk.custom.PreviewOperatorListener
import com.vc.videosdk.interfaces.VcStreamListener
import com.vc.videosdk.utils.SteamKeyboardUtil
import com.vc.videosdk.utils.SteamKeyboardUtil.Companion.getInstance
import com.vc.videosdk.xlog.XLogUtil
import org.vclusters.network.NetWork
import java.io.File
import java.io.FileOutputStream
import java.io.IOException


class StreamActivity : Activity(), VcStreamListener,
    ControlDialog.OnMenuClickListener, View.OnClickListener {

    private var name = ""
    private var room_uri = ""
    private var room_name = ""

    var codec = ""
    var bitrate = ""
    var esize = ""
    var fps = ""
    var localVideoCallEnabled = false
    var localAudioCallEnabled = false
    var localVideoReceiveEnabled = false
    var localAudioReceiveEnabled = false
    var remoteVideoCallEnabled = false
    var remoteAudioCallEnabled = false
    var remoteVideoReceiveEnabled = false
    var remoteAudioReceiveEnabled = false
    var width = 0
    var height = 0
    var density = 480
    var cardWidth = 1080
    var cardHeight = 1920;
    var gpsDelay = 300
    var token = "vclusters"

    private var controlDialog: ControlDialog? = null
    private var mStartAppDialog: StartAppDialog? = null
    private var mStopAppDialog: StopAppDialog? = null
    private var mUninstallAppDialog: UninstallAppDialog? = null
    private var mHideAppDialog: HideAppDialog? = null
    private var mDisplayAppDialog: DisplayAppDialog? = null
    private var mAppRootDialog: AppRootDialog? = null
    private var mSystemRootDialog: SystemRootDialog? = null
    private var mVirtualLocationDialog: VirtualLocationDialog? = null
    private var mSettingResolutionDialog: SettingResolutionDialog? = null
    private var mClipboardDialog: ClipboardDialog? = null
    private var mStartPreviewDialog: StartPreviewDialog? = null
    private var mStopPreviewDialog: StopPreviewDialog? = null
    private var mSettingDpiDialog: SettingDpiDialog? = null

    var TAG: String = "StreamActivity"
    private var mVcSurfaceView: VcSurfaceView? = null
    private var iv_menu: ImageView? = null
    private var iv_home: ImageView? = null
    private var iv_back: ImageView? = null
    private var ll_function_control_view: LinearLayout? = null
    private var bt_start_app: Button? = null
    private var bt_stop_app: Button? = null
    private var bt_uninstall_app: Button? = null
    private var bt_hide_app: Button? = null
    private var bt_display_app: Button? = null
    private var bt_sys_resolution:Button?=null
    private var bt_dpi:Button?=null


    private var bt_root_app: Button? = null
    private var bt_root_sys: Button? = null
    private var bt_virtual_location: Button? = null
    private var bt_sys_clipboard: Button? = null
    private var bt_sys_preview_start: Button? = null
    private var bt_sys_preview_stop: Button? = null
    private var iv_picture1: ImageView? = null
    private var iv_picture2: ImageView? = null
    private var ll_picture: LinearLayout? = null
    private var mEdtKeyboard:EditText?=null
    private var sessionId:String?=null

    private var cloud_phone_suspension: SuspensionView? = null

    private fun getSystemUiVisibility(): Int {
        return (View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN
                or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
    }

    @SuppressLint("HandlerLeak")
    private val mHandler: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what == VideoConstant.OPEN_DIALOG_CONTROL) {
                if (controlDialog != null) {
                    Log.d(TAG, "handleMessage");
                    controlDialog!!.show(this@StreamActivity)
                }
            }
        }
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        setContentView(R.layout.activity_stream)
        XLogUtil.d("VC_SDK_VERSION:${Constant.VC_SDK_VERSION}")
        cloud_phone_suspension = findViewById(R.id.cloud_phone_suspension)
        iv_menu = findViewById(R.id.iv_menu)
        iv_home = findViewById(R.id.iv_home)
        iv_back = findViewById(R.id.iv_back)
        mVcSurfaceView = findViewById(R.id.vc_surfaceview)
        ll_function_control_view = findViewById(R.id.ll_function_control_view)
        ll_picture = findViewById(R.id.ll_picture)
        mEdtKeyboard=findViewById(R.id.edt_keyboard_input)


        bt_start_app = findViewById(R.id.bt_start_app)
        bt_stop_app = findViewById(R.id.bt_stop_app)
        bt_uninstall_app = findViewById(R.id.bt_uninstall_app)
        bt_hide_app = findViewById(R.id.bt_hide_app)
        bt_display_app = findViewById(R.id.bt_display_app)
        bt_root_app = findViewById(R.id.bt_root_app)
        bt_root_sys = findViewById(R.id.bt_root_sys)
        bt_virtual_location = findViewById(R.id.bt_virtual_location)
        bt_sys_clipboard = findViewById(R.id.bt_sys_clipboard)
        bt_sys_preview_start = findViewById(R.id.bt_sys_preview_start)
        bt_sys_preview_stop = findViewById(R.id.bt_sys_preview_stop)
        iv_picture1 = findViewById(R.id.iv_picture1)
        iv_picture2 = findViewById(R.id.iv_picture2)
        bt_dpi=findViewById(R.id.bt_dpi)
        bt_sys_resolution=findViewById(R.id.bt_sys_resolution)

        bt_start_app?.setOnClickListener(this)
        bt_stop_app?.setOnClickListener(this)
        bt_uninstall_app?.setOnClickListener(this)
        bt_hide_app?.setOnClickListener(this)
        bt_display_app?.setOnClickListener(this)
        bt_root_app?.setOnClickListener(this)
        bt_root_sys?.setOnClickListener(this)
        bt_virtual_location?.setOnClickListener(this)
        bt_sys_clipboard?.setOnClickListener(this)
        bt_sys_preview_start?.setOnClickListener(this)
        bt_sys_preview_stop?.setOnClickListener(this)
        bt_dpi?.setOnClickListener(this)
        bt_sys_resolution?.setOnClickListener(this)

        controlDialog = ControlDialog()
        controlDialog?.setOnMenuClickListener(this)
        Build.VERSION_CODES.Q
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            window.addFlags(
                LayoutParams.FLAG_TRANSLUCENT_STATUS
            )
        }

        cloud_phone_suspension?.setOnSuspensionViewClickListener {
            Log.d(TAG, "setOnSuspensionViewClickListener");
            val message = mHandler.obtainMessage(VideoConstant.OPEN_DIALOG_CONTROL)
            mHandler.sendMessage(message)
        }

        iv_menu?.setOnClickListener() {
            if (SharedPHelper.getInstance(this)
                    .getBooleanWithDefaultTrue(VideoConstant.BOTTOM_LEFT_SWITCH)
            ) {
                mVcSurfaceView?.sendKey(VideoConstant.KEY_MENU.toInt())
            } else {
                mVcSurfaceView?.sendKey(VideoConstant.KEY_BACK.toInt())
            }
        }

        iv_home?.setOnClickListener {
            mVcSurfaceView?.sendKey(VideoConstant.KEY_HOME.toInt())
        }

        iv_back?.setOnClickListener {
            if (SharedPHelper.getInstance(this)
                    .getBooleanWithDefaultTrue(VideoConstant.BOTTOM_LEFT_SWITCH)
            ) {
                mVcSurfaceView?.sendKey(VideoConstant.KEY_BACK.toInt())
            } else {
                mVcSurfaceView?.sendKey(VideoConstant.KEY_MENU.toInt())
            }
        }


        val intent = intent
        room_uri = intent.getStringExtra("uri").toString()
        room_name = intent.getStringExtra("room").toString()
        token = intent.getStringExtra("auths").toString()
        codec = intent.getStringExtra("videocodec").toString()
        bitrate = intent.getStringExtra("bitrate").toString()
        esize = intent.getStringExtra("encodeSize").toString()
        fps = intent.getStringExtra("videofps").toString()
        sessionId=intent.getStringExtra("sessionId").toString()

        localVideoCallEnabled = intent.getBooleanExtra("localVideoCallEnabled", false)
        localAudioCallEnabled = intent.getBooleanExtra("localAudioCallEnabled", false)
        localVideoReceiveEnabled = intent.getBooleanExtra("localVideoReceiveEnabled", false)
        localAudioReceiveEnabled = intent.getBooleanExtra("localAudioReceiveEnabled", false)
        remoteVideoCallEnabled = intent.getBooleanExtra("remoteVideoCallEnabled", false)
        remoteAudioCallEnabled = intent.getBooleanExtra("remoteAudioCallEnabled", false)
        remoteVideoReceiveEnabled = intent.getBooleanExtra("remoteVideoReceiveEnabled", false)
        remoteAudioReceiveEnabled = intent.getBooleanExtra("remoteAudioReceiveEnabled", false)
        width = intent.getIntExtra("width", 1280)
        height = intent.getIntExtra("height", 720)
        density = intent.getIntExtra("density", 480)
        cardWidth = intent.getIntExtra("cardWidth", 1080)
        cardHeight = intent.getIntExtra("cardHeight", 1920)
        gpsDelay = intent.getIntExtra("gpsDelay", 300)

        Log.d(
            TAG,
            "localVideoCallEnabled:$localVideoCallEnabled localAudioCallEnabled:$localAudioCallEnabled" +
                    "  localVideoReceiveEnabled:$localVideoReceiveEnabled localAudioReceiveEnabled:$localAudioReceiveEnabled" +
                    "  remoteVideoCallEnabled:$remoteVideoCallEnabled remoteAudioCallEnabled:$remoteAudioCallEnabled" +
                    "  remoteVideoReceiveEnabled:$remoteVideoReceiveEnabled remoteAudioReceiveEnabled:$remoteAudioReceiveEnabled"
        )
        mVcSurfaceView?.setActivity(this)
        mVcSurfaceView?.setVcStreamListener(this)


        val iceServers: HashMap<NetWork.NETWORKNAME, String> =
            HashMap<NetWork.NETWORKNAME, String>() //define empty hashmap
//        iceServers.put(NetWork.NETWORKNAME.CMNET, "14.18.190.138:19301")
//        iceServers.put(NetWork.NETWORKNAME.CHINANET, "14.18.190.138:19301")
//        iceServers.put(NetWork.NETWORKNAME.UNICOM, "14.18.190.138:19301")

        iceServers.put(NetWork.NETWORKNAME.CMNET, "115.227.9.120:3478")
        iceServers.put(NetWork.NETWORKNAME.CHINANET, "115.227.9.120:3478")
        iceServers.put(NetWork.NETWORKNAME.UNICOM, "115.227.9.120:3478")


        mVcSurfaceView?.setIceServer(iceServers)
        name = mVcSurfaceView?.startConnect(
            room_uri,
            room_name,
            codec,
            fps.toInt(),
            bitrate.toInt(),
            width,
            height,
            cardWidth,
            cardHeight,
            density,
            token
        ).toString()


        mEdtKeyboard?. let {
           mVcSurfaceView?.setCloubKeyEdt(it)
        }
        Log.d(TAG, "name:" + name);
    }

    override fun onMenuClick(menuType: Int, entity: String?) {
        val ret = false
        Log.d(TAG, "onMenuClick:$menuType")
        when (menuType) {
            VideoConstant.APP_VOLUME_DOWN -> mVcSurfaceView?.sendKey(VideoConstant.KEY_VOLUME_DOWN.toInt())
            VideoConstant.APP_VOLUME_UP -> mVcSurfaceView?.sendKey(VideoConstant.KEY_VOLUME_UP.toInt())
            VideoConstant.BTN_EXIT -> {
                mVcSurfaceView?.stopConnect()
              exit()
            }

            VideoConstant.SWITCH_PATTERN -> setBottomSwitch()
            VideoConstant.APP_FINGER_CONTROL -> setFingerControl()
            VideoConstant.APP_FUNCTION_CONTROL -> setFunctionControl()
        }
    }

    override fun onBackPressed() {
        super.onBackPressed()
        XLogUtil.d("onBackPressed")
       exit()
    }

    private fun exit(){
        XLogUtil.d("StreamActivity exit() sessionId:$sessionId")
        if(sessionId!=null){
            ApiJavaClient.cancelGroupControl(sessionId!!, object : ICallback<Any> {
                override fun onSuccess(obj: Any) {
                    XLogUtil.d("cancelGroupControl onSuccess :$obj")
                    Toast.makeText(this@StreamActivity,"注销群控会话成功",Toast.LENGTH_SHORT).show()
                    finish()
                }

                override fun onFailed(code: String, msg: String) {
                    XLogUtil.e("cancelGroupControl onFailed code:$code,,,msg:$msg,,,sessionId:$sessionId")
                    Toast.makeText(this@StreamActivity,"注销群控会话失败，请手动注销",Toast.LENGTH_SHORT).show()
                    finish()
                }
            })
        }else{
            finish()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mVcSurfaceView?.stopConnect()
    }

    private fun setBottomSwitch() {
        if (SharedPHelper.getInstance(this)
                .getBooleanWithDefaultTrue(VideoConstant.BOTTOM_SWITCH)
        ) {
            Log.d(TAG, "setBottomSwitch:VISIBLE")
            iv_menu?.visibility = View.VISIBLE
            iv_back?.visibility = View.VISIBLE
            iv_home?.visibility = View.VISIBLE
        } else {
            Log.d(TAG, "setBottomSwitch:GONE")
            iv_menu?.visibility = View.GONE
            iv_back?.visibility = View.GONE
            iv_home?.visibility = View.GONE
        }
    }

    private fun setFingerControl() {
        if (SharedPHelper.getInstance(this)
                .getBooleanWithDefaultTrue(VideoConstant.BOTTOM_LEFT_SWITCH)
        ) {
            iv_back?.setImageResource(R.mipmap.ic_app_back)
            iv_menu?.setImageResource(R.mipmap.ic_app_switch)
            iv_home?.setImageResource(R.mipmap.ic_app_home)
        } else {
            iv_back?.setImageResource(R.mipmap.ic_app_switch)
            iv_menu?.setImageResource(R.mipmap.ic_app_back)
            iv_home?.setImageResource(R.mipmap.ic_app_home)
        }
    }

    private fun setFunctionControl() {
        if (SharedPHelper.getInstance(this)
                .getBooleanWithDefaultTrue(VideoConstant.BOTTOM_FUNCTION_SWITCH)
        ) {
            ll_function_control_view?.visibility = View.VISIBLE
        } else {
            ll_function_control_view?.visibility = View.GONE
        }
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.bt_start_app -> showStartApp()
            R.id.bt_stop_app -> showStopApp()
            R.id.bt_uninstall_app -> showUninstallApp()
            R.id.bt_hide_app -> showHideApp()
            R.id.bt_display_app -> showDisplayApp()
            R.id.bt_root_app -> showAppRoot()
            R.id.bt_root_sys -> showSysRoot()
            R.id.bt_virtual_location -> showVirtualLocation()
            R.id.bt_sys_clipboard -> showClipboard()
            R.id.bt_sys_preview_start -> showStartPreview()
            R.id.bt_sys_preview_stop -> showStopPriview()
            R.id.bt_sys_resolution->showSettingResolution()
            R.id.bt_dpi->showSettingDpi()
        }
    }


    /**
     * 启动应用
     */
    private fun showStartApp() {
        if (mStartAppDialog == null) {
            mStartAppDialog = StartAppDialog()
        }
        mStartAppDialog!!.show(this@StreamActivity, object : IRequesListener1 {
            override fun onRequestParam(
                instanceId: String,
                ip: String,
                token: String,
                packageName: String
            ) {
                XLogUtil.d("showStartApp instanceId:$instanceId,,,ip:$ip,,,token:$token,,,packageName:$packageName")
                val instanceIdList = instanceId.split(",")
                val ipList = ip.split(",")
                val tokenList = token.split(",")
                val packageNameList = packageName.split(",")

                if (instanceIdList.size != ipList.size || instanceIdList.size != tokenList.size
                    || instanceIdList.size != packageNameList.size
                ) {
                    Toast.makeText(this@StreamActivity, "参数个数要一致", Toast.LENGTH_SHORT).show()
                    return
                }

                for (i in instanceIdList.indices) {
                    val instanceId = instanceIdList[i]
                    val ip = ipList[i]
                    val token = tokenList[i]
                    val packageName = packageNameList[i]
                    VcOperateManager.getInstance().startApp(
                        instanceId,
                        ip,
                        token,
                        packageName,
                        object : OperatorListener {
                            override fun operatorResult(
                                instanceId: String,
                                code: Int,
                                message: String
                            ) {
                                XLogUtil.d("startApp result code:$code,,,message:$message,,,instanceId:$instanceId")
                                runOnUiThread {
                                    Toast.makeText(this@StreamActivity, message, Toast.LENGTH_LONG)
                                        .show()
                                }
                            }
                        })
                }
            }
        })
    }


    /**
     * 停止应用
     */
    private fun showStopApp() {
        if (mStopAppDialog == null) {
            mStopAppDialog = StopAppDialog()
        }
        mStopAppDialog!!.show(this@StreamActivity, object : IRequesListener1 {
            override fun onRequestParam(
                instanceId: String,
                ip: String,
                token: String,
                packageName: String
            ) {
                XLogUtil.d("showStopApp instanceId:$instanceId,,,ip:$ip,,,token:$token,,,packageName:$packageName")

                val instanceIdList = instanceId.split(",")
                val ipList = ip.split(",")
                val tokenList = token.split(",")
                val packageNameList = packageName.split(",")

                if (instanceIdList.size != ipList.size || instanceIdList.size != tokenList.size
                    || instanceIdList.size != packageNameList.size
                ) {
                    Toast.makeText(this@StreamActivity, "参数个数要一致", Toast.LENGTH_SHORT).show()
                    return
                }

                if (instanceIdList.size != ipList.size || instanceIdList.size != tokenList.size
                    || instanceIdList.size != packageNameList.size
                ) {
                    Toast.makeText(this@StreamActivity, "参数个数要一致", Toast.LENGTH_SHORT).show()
                    return
                }



                for (i in instanceIdList.indices) {
                    val instanceId = instanceIdList[i]
                    val ip = ipList[i]
                    val token = tokenList[i]
                    val packageName = packageNameList[i]

                    VcOperateManager.getInstance().stopApp(
                        instanceId,
                        ip,
                        token,
                        packageName,
                        object : OperatorListener {
                            override fun operatorResult(
                                instanceId: String,
                                code: Int,
                                message: String
                            ) {
                                XLogUtil.d("stopApp result code:$code,,,message:$message")
                                runOnUiThread {
                                    Toast.makeText(this@StreamActivity, message, Toast.LENGTH_LONG)
                                        .show()
                                }
                            }
                        })
                }
            }
        })
    }


    /**
     * 卸载应用
     */
    private fun showUninstallApp() {
        if (mUninstallAppDialog == null) {
            mUninstallAppDialog = UninstallAppDialog()
        }
        mUninstallAppDialog!!.show(this@StreamActivity, object : IRequesListener1 {
            override fun onRequestParam(
                instanceId: String,
                ip: String,
                token: String,
                packageName: String
            ) {
                XLogUtil.d("showUninstallApp instanceId:$instanceId,,,ip:$ip,,,token:$token,,,packageName:$packageName")

                val instanceIdList = instanceId.split(",")
                val ipList = ip.split(",")
                val tokenList = token.split(",")
                val packageNameList = packageName.split(",")

                if (instanceIdList.size != ipList.size || instanceIdList.size != tokenList.size
                    || instanceIdList.size != packageNameList.size
                ) {
                    Toast.makeText(this@StreamActivity, "参数个数要一致", Toast.LENGTH_SHORT).show()
                    return
                }

                for (i in instanceIdList.indices) {
                    val instanceId = instanceIdList[i]
                    val ip = ipList[i]
                    val token = tokenList[i]
                    val packageName = packageNameList[i]

                    VcOperateManager.getInstance().unInstallApp(
                        instanceId,
                        ip,
                        token,
                        packageName,
                        object : OperatorListener {
                            override fun operatorResult(
                                instanceId: String,
                                code: Int,
                                message: String
                            ) {
                                XLogUtil.d("unInstallApp result code:$code,,,message:$message")
                                runOnUiThread {
                                    Toast.makeText(this@StreamActivity, message, Toast.LENGTH_LONG)
                                        .show()
                                }
                            }
                        })

                }

            }
        })
    }

    /**
     * 隐藏应用
     */
    private fun showHideApp() {
        if (mHideAppDialog == null) {
            mHideAppDialog = HideAppDialog()
        }
        mHideAppDialog!!.show(this@StreamActivity, object : IRequesListener2 {
            override fun onRequestParam(
                instanceId: String,
                ip: String,
                token: String
            ) {
                XLogUtil.d("showHideApp instanceId:$instanceId,,,ip:$ip,,,token:$token")

                val instanceIdList = instanceId.split(",")
                val ipList = ip.split(",")
                val tokenList = token.split(",")

                if (instanceIdList.size != ipList.size || instanceIdList.size != tokenList.size) {
                    Toast.makeText(this@StreamActivity, "参数个数要一致", Toast.LENGTH_SHORT).show()
                    return
                }


                for (i in instanceIdList.indices) {
                    val instanceId = instanceIdList[i]
                    val ip = ipList[i]
                    val token = tokenList[i]
                    VcOperateManager.getInstance().hideApp(
                        instanceId,
                        ip,
                        token,
                        object : OperatorListener {
                            override fun operatorResult(
                                instanceId: String,
                                code: Int,
                                message: String
                            ) {
                                XLogUtil.d("hideApp result code:$code,,,message:$message")
                                runOnUiThread {
                                    Toast.makeText(this@StreamActivity, message, Toast.LENGTH_LONG)
                                        .show()
                                }
                            }
                        })

                }

            }
        })
    }


    /**
     * 显示应用
     */
    private fun showDisplayApp() {
        if (mDisplayAppDialog == null) {
            mDisplayAppDialog = DisplayAppDialog()
        }
        mDisplayAppDialog!!.show(this@StreamActivity, object : IRequesListener2 {
            override fun onRequestParam(
                instanceId: String,
                ip: String,
                token: String
            ) {
                XLogUtil.d("showDisplayApp instanceId:$instanceId,,,ip:$ip,,,token:$token")

                val instanceIdList = instanceId.split(",")
                val ipList = ip.split(",")
                val tokenList = token.split(",")

                if (instanceIdList.size != ipList.size || instanceIdList.size != tokenList.size) {
                    Toast.makeText(this@StreamActivity, "参数个数要一致", Toast.LENGTH_SHORT).show()
                    return
                }


                for (i in instanceIdList.indices) {
                    val instanceId = instanceIdList[i]
                    val ip = ipList[i]
                    val token = tokenList[i]
                    VcOperateManager.getInstance().displayApp(
                        instanceId,
                        ip,
                        token,
                        object : OperatorListener {
                            override fun operatorResult(
                                instanceId: String,
                                code: Int,
                                message: String
                            ) {
                                XLogUtil.d("displayApp result code:$code,,,message:$message")
                                runOnUiThread {
                                    Toast.makeText(this@StreamActivity, message, Toast.LENGTH_LONG)
                                        .show()
                                }
                            }
                        })
                }
            }
        })
    }


    /**
     * 应用root设置
     */
    private fun showAppRoot() {
        if (mAppRootDialog == null) {
            mAppRootDialog = AppRootDialog()
        }
        mAppRootDialog!!.show(this@StreamActivity, object : IRequesListener3 {
            override fun onRequestParam(
                instanceId: String,
                ip: String,
                token: String,
                rootSwitch: String,
                packageName: String
            ) {
                XLogUtil.d("showAppRoot instanceId:$instanceId,,,ip:$ip,,,token:$token,,,rootSwitch:$rootSwitch,,,packageName:$packageName")


                val instanceIdList = instanceId.split(",")
                val ipList = ip.split(",")
                val tokenList = token.split(",")
                val rootSwitchList = rootSwitch.split(",")
                val packageLists = packageName.split(",")

                if (instanceIdList.size != ipList.size || instanceIdList.size != tokenList.size
                    || instanceIdList.size != rootSwitchList.size
                ) {
                    Toast.makeText(this@StreamActivity, "参数个数要一致", Toast.LENGTH_SHORT).show()
                    return
                }


                for (i in instanceIdList.indices) {
                    val instanceId = instanceIdList[i]
                    val ip = ipList[i]
                    val token = tokenList[i]
                    val rootSwitch = rootSwitchList[i]

                    VcOperateManager.getInstance().rootApp(
                        instanceId,
                        ip,
                        token,
                        rootSwitch.toInt(),
                        packageLists,
                        object : OperatorListener {
                            override fun operatorResult(
                                instanceId: String,
                                code: Int,
                                message: String
                            ) {
                                XLogUtil.d("rootApp result code:$code,,,message:$message")
                                runOnUiThread {
                                    Toast.makeText(this@StreamActivity, message, Toast.LENGTH_LONG)
                                        .show()
                                }
                            }
                        })
                }

            }
        })
    }


    /**
     * 全局root
     */
    private fun showSysRoot() {
        if (mSystemRootDialog == null) {
            mSystemRootDialog = SystemRootDialog()
        }
        mSystemRootDialog!!.show(this@StreamActivity, object : IRequesListener4 {
            override fun onRequestParam(
                instanceId: String,
                ip: String,
                token: String,
                rootSwitch: String
            ) {
                XLogUtil.d("showSysRoot instanceId:$instanceId,,,ip:$ip,,,token:$token,,,rootSwitch:$rootSwitch")

                val instanceIdList = instanceId.split(",")
                val ipList = ip.split(",")
                val tokenList = token.split(",")
                val rootSwitchList = rootSwitch.split(",")

                if (instanceIdList.size != ipList.size || instanceIdList.size != tokenList.size
                    || instanceIdList.size != rootSwitchList.size
                ) {
                    Toast.makeText(this@StreamActivity, "参数个数要一致", Toast.LENGTH_SHORT).show()
                    return
                }

                for (i in instanceIdList.indices) {
                    val instanceId = instanceIdList[i]
                    val ip = ipList[i]
                    val token = tokenList[i]
                    val rootSwitch = rootSwitchList[i]

                    VcOperateManager.getInstance().systemRoot(
                        instanceId,
                        ip,
                        token,
                        rootSwitch.toInt(),
                        object : OperatorListener {
                            override fun operatorResult(
                                instanceId: String,
                                code: Int,
                                message: String
                            ) {
                                XLogUtil.d("systemRoot result code:$code,,,message:$message")
                                runOnUiThread {
                                    Toast.makeText(this@StreamActivity, message, Toast.LENGTH_LONG)
                                        .show()
                                }
                            }
                        })
                }

            }
        })
    }


    /**
     * 虚拟定位
     */
    private fun showVirtualLocation() {
        if (mVirtualLocationDialog == null) {
            mVirtualLocationDialog = VirtualLocationDialog()
        }
        mVirtualLocationDialog!!.show(this@StreamActivity, object : IRequesListener5 {
            override fun onRequestParam(
                instanceId: String,
                ip: String,
                token: String,
                longitude: String,
                latitude: String
            ) {
                XLogUtil.d("showVirtualLocation instanceId:$instanceId,,,ip:$ip,,,token:$token,,,longitude:$longitude,,,latitude:$latitude")
                val instanceIdList = instanceId.split(",")
                val ipList = ip.split(",")
                val tokenList = token.split(",")
                val longitudeList = longitude.split(",")
                val latitudeList = latitude.split(",")

                if (instanceIdList.size != ipList.size || instanceIdList.size != tokenList.size
                    || instanceIdList.size != longitudeList.size ||
                    instanceIdList.size != latitudeList.size
                ) {
                    Toast.makeText(this@StreamActivity, "参数个数要一致", Toast.LENGTH_SHORT).show()
                    return
                }

                for (i in instanceIdList.indices) {
                    val instanceId = instanceIdList[i]
                    val ip = ipList[i]
                    val token = tokenList[i]
                    val longitude = longitudeList[i]
                    val latitude = latitudeList[i]

                    VcOperateManager.getInstance().virtualLocation(
                        instanceId,
                        ip,
                        token,
                        longitude,
                        latitude,
                        object : OperatorListener {
                            override fun operatorResult(
                                instanceId: String,
                                code: Int,
                                message: String
                            ) {
                                XLogUtil.d("virtualLocation result code:$code,,,message:$message")
                                runOnUiThread {
                                    Toast.makeText(this@StreamActivity, message, Toast.LENGTH_LONG)
                                        .show()
                                }
                            }
                        })
                }
            }
        })
    }


    /**
     * 剪切板内容发送
     */
    private fun showClipboard() {
        if (mClipboardDialog == null) {
            mClipboardDialog = ClipboardDialog()
        }

        mClipboardDialog!!.show(this@StreamActivity, object : IRequesListener6 {
            override fun onRequestParam(
                instanceId: String,
                ip: String,
                token: String,
                content: String,
            ) {
                XLogUtil.d("showClipboard instanceId:$instanceId,,,ip:$ip,,,token:$token,,,content:$content")

                val instanceIdList = instanceId.split(",")
                val ipList = ip.split(",")
                val tokenList = token.split(",")
                val contentList = content.split(",")

                if (instanceIdList.size != ipList.size || instanceIdList.size != tokenList.size
                    || instanceIdList.size != contentList.size
                ) {
                    Toast.makeText(this@StreamActivity, "参数个数要一致", Toast.LENGTH_SHORT).show()
                    return
                }

                for (i in instanceIdList.indices) {
                    val instanceId = instanceIdList[i]
                    val ip = ipList[i]
                    val token = tokenList[i]
                    val content = contentList[i]

                    VcOperateManager.getInstance().clipBoard(
                        instanceId,
                        ip,
                        token,
                        content,
                        object : OperatorListener {
                            override fun operatorResult(
                                instanceId: String,
                                code: Int,
                                message: String
                            ) {
                                XLogUtil.d("clipBoard result code:$code,,,message:$message")
                                runOnUiThread {
                                    Toast.makeText(this@StreamActivity, message, Toast.LENGTH_LONG)
                                        .show()
                                }
                            }
                        })
                }
            }
        })
    }


    /**
     * 开启预览图
     */
    private fun showStartPreview() {
        // fileNumber++
        if (mStartPreviewDialog == null) {
            mStartPreviewDialog = StartPreviewDialog()
        }

        mStartPreviewDialog!!.show(this@StreamActivity, object : IRequesListener7 {
            override fun onRequestParam(
                instanceId: String,
                ip: String,
                token: String,
                interval: String,
                width: String,
                height: String,
                quality: String
            ) {
                XLogUtil.d("showStartPreview instanceId:$instanceId,,,ip:$ip,,,token:$token,,,interval:$interval,,,width:$width,,,height:$height,,,quality:$quality")
                VcOperateManager.getInstance().sysPreviewStart(
                    instanceId,
                    ip,
                    token,
                    interval,
                    width,
                    height,
                    quality,
                    object : PreviewOperatorListener {
                        override fun operatorResult(
                            instanceId: String,
                            code: Int,
                            type: String,
                            message: String
                        ) {
                            XLogUtil.d("showStartPreview result code:$code,,,message:$message")
                            runOnUiThread {
                                if (type.isNotEmpty()) {
                                    if (type == Constant.SYSTEM_PREVIEW_START) {
                                        iv_picture1?.visibility = View.VISIBLE
                                    } else {
                                        iv_picture1?.visibility = View.GONE
                                    }
                                } else {
                                    iv_picture1?.visibility = View.GONE
                                }

                                Toast.makeText(this@StreamActivity, message, Toast.LENGTH_LONG)
                                    .show()
                            }
                        }

                        override fun previewData(bitmap: Bitmap) {
                            XLogUtil.d("showStartPreview previewData$bitmap,,,width:${bitmap.width},,,,height:${bitmap.height}")
                            // saveBitmapToJpg(bitmap,"preview")
                            runOnUiThread {
                                iv_picture1?.let {
                                    loadBitmapImage(it, bitmap)
                                }
                            }
                        }
                    })
            }
        })
    }


    /**
     * 停止预览图推流
     */
    private fun showStopPriview() {
        if (mStopPreviewDialog == null) {
            mStopPreviewDialog = StopPreviewDialog()
        }

        mStopPreviewDialog!!.show(this@StreamActivity, object : IRequesListener2 {
            override fun onRequestParam(
                instanceId: String,
                ip: String,
                token: String,
            ) {
                XLogUtil.d("showStopPriview instanceId:$instanceId,,,ip:$ip,,,token:$token")
                iv_picture1?.visibility = View.GONE
                VcOperateManager.getInstance().sysPreviewStop(
                    instanceId,
                    ip,
                    token,
                    object : OperatorListener {
                        override fun operatorResult(
                            instanceId: String,
                            code: Int,
                            message: String
                        ) {
                            XLogUtil.d("sysPreviewStop result code:$code,,,message:$message")
                            runOnUiThread {
                                iv_picture1?.visibility = View.GONE
                                Toast.makeText(this@StreamActivity, message, Toast.LENGTH_LONG)
                                    .show()
                            }
                        }
                    })
            }
        })
    }



    //设置卡分辨率
    private fun showSettingResolution() {
        if (mSettingResolutionDialog == null) {
            mSettingResolutionDialog = SettingResolutionDialog()
        }
        mSettingResolutionDialog!!.show(this@StreamActivity, object : IRequesListener5 {
            override fun onRequestParam(
                instanceId: String,
                ip: String,
                token: String,
                width: String,
                height: String
            ) {
                XLogUtil.d("showSettingResolution instanceId:$instanceId,,,ip:$ip,,,token:$token,,,width:$width,,,latitude:$height")
                val instanceIdList = instanceId.split(",")
                val ipList = ip.split(",")
                val tokenList = token.split(",")
                val widthList = width.split(",")
                val heightList = height.split(",")

                if (instanceIdList.size != ipList.size || instanceIdList.size != tokenList.size
                    || instanceIdList.size != widthList.size ||
                    instanceIdList.size != heightList.size
                ) {
                    Toast.makeText(this@StreamActivity, "参数个数要一致", Toast.LENGTH_SHORT).show()
                    return
                }

                for (i in instanceIdList.indices) {
                    val instanceId = instanceIdList[i]
                    val ip = ipList[i]
                    val token = tokenList[i]
                    val width = widthList[i]
                    val height = heightList[i]

                    VcOperateManager.getInstance().sysResolution(
                        instanceId,
                        ip,
                        token,
                        width,
                        height,
                        object : OperatorListener {
                            override fun operatorResult(
                                instanceId: String,
                                code: Int,
                                message: String
                            ) {
                                XLogUtil.d("sysResolution result code:$code,,,message:$message")
                                runOnUiThread {
                                    Toast.makeText(this@StreamActivity, message, Toast.LENGTH_LONG)
                                        .show()
                                }
                            }
                        })
                }
            }
        })
    }


    /**
     * 设置dpi
     */
    private fun showSettingDpi() {
        if (mSettingDpiDialog == null) {
            mSettingDpiDialog = SettingDpiDialog()
        }
        mSettingDpiDialog!!.show(this@StreamActivity, object : IRequesListener1 {
            override fun onRequestParam(
                instanceId: String,
                ip: String,
                token: String,
                dpi: String
            ) {
                XLogUtil.d("showSettingDpi instanceId:$instanceId,,,ip:$ip,,,token:$token,,,dpi:$dpi")
                val instanceIdList = instanceId.split(",")
                val ipList = ip.split(",")
                val tokenList = token.split(",")
                val dpiList = dpi.split(",")

                if (instanceIdList.size != ipList.size || instanceIdList.size != tokenList.size
                    || instanceIdList.size != dpiList.size
                ) {
                    Toast.makeText(this@StreamActivity, "参数个数要一致", Toast.LENGTH_SHORT).show()
                    return
                }

                for (i in instanceIdList.indices) {
                    val instanceId = instanceIdList[i]
                    val ip = ipList[i]
                    val token = tokenList[i]
                    val dpi = dpiList[i]
                    VcOperateManager.getInstance().sysDpi(
                        instanceId,
                        ip,
                        token,
                        dpi,
                        object : OperatorListener {
                            override fun operatorResult(
                                instanceId: String,
                                code: Int,
                                message: String
                            ) {
                                XLogUtil.d("sysDpi result code:$code,,,message:$message,,,instanceId:$instanceId")
                                runOnUiThread {
                                    Toast.makeText(this@StreamActivity, message, Toast.LENGTH_LONG)
                                        .show()
                                }
                            }
                        })
                }
            }
        })
    }


    fun loadBitmapImage(target: ImageView, bitmap: Bitmap) {
        val drawable = BitmapDrawable(target.resources, bitmap)
        val requestOptions = RequestOptions().centerCrop()
            .diskCacheStrategy(DiskCacheStrategy.NONE)
            .error(drawable)
            .placeholder(drawable)

        Glide.with(target.context)
            .setDefaultRequestOptions(requestOptions)
            .load("https://${System.currentTimeMillis()}")//随便给个不可用的url
            .into(target)
    }

    var fileNumber = 0
    fun saveBitmapToJpg(bitmap: Bitmap, name: String?) {
        var fileName = name + "_$fileNumber.jpg"
        // 创建保存图片的目录
//        val picturesDirectory =
//            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)

        val picturesDirectory =
            Environment.getExternalStorageDirectory().path + "/vc_video"
        val imageFile = File(picturesDirectory, fileName)
        var outputStream: FileOutputStream? = null
        try {
            outputStream = FileOutputStream(imageFile)
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
            outputStream.flush()
            outputStream.close()
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            try {
                outputStream?.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

    override fun onDisConnected(peerName: String) {
        //信令服务器异常
        Toast.makeText(this@StreamActivity,"连接异常",Toast.LENGTH_SHORT).show()
//        if (peerName == name) {
//            mVcSurfaceView?.stopConnect()
//        }
        //finish()
    }

    override fun onAuthResult(peerName: String, code: Int, descriptions: String) {
        XLogUtil.d("onAuthResult peerName:$peerName code:$code descriptions:$descriptions")
    }

    override fun onIceConnected(peerName: String) {

    }
}